package com.tinysand.advert.service.impl;

import com.tinysand.advert.constant.SystemConstant;
import com.tinysand.advert.entity.AdvertUser;
import com.tinysand.advert.exception.AdvertException;
import com.tinysand.advert.repository.UserRepository;
import com.tinysand.advert.service.UserService;
import com.tinysand.advert.support.CreateUserRequest;
import com.tinysand.advert.support.UserCreatedResponse;
import com.tinysand.advert.utils.CommonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 用户创建服务接口实现
 *
 * Created By TINY
 * Create Time 2020/2/21
 **/
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    /* 用户数据持久层对象 */
    private final UserRepository userRepository;

    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    /**
     * 创建一个用户，并以指定格式返回创建结果
     *
     * @param request 用户创建对象请求 {@link CreateUserRequest}
     * @return 用户创建结果 {@link UserCreatedResponse}
     * @throws AdvertException 业务异常
     */
    @Override
    public UserCreatedResponse createUser(
            CreateUserRequest request) throws AdvertException {

        if (!request.validate()) {
            throw new AdvertException(
                    SystemConstant.Error.REQUEST_PARAM_ERROR);
        }

        AdvertUser oldUser = userRepository
                .findByUsername(request.getUsername());

        if (null != oldUser) {
            throw new AdvertException(SystemConstant.Error.SAME_NAME_ERROR);
        }

        AdvertUser newUser = userRepository.save(new AdvertUser(
                request.getUsername(),
                CommonUtils.md5(request.getUsername())
        ));

        return new UserCreatedResponse(
                newUser.getId(),
                newUser.getUsername(),
                newUser.getToken(),
                newUser.getCreateTime(),
                newUser.getUpdateTime()
        );
    }
}
